//
//  MusicPlayViewController.m
//  JZMCFM
//
//  Created by Mc on 15/11/3.
//  Copyright (c) 2015年 陈卓. All rights reserved.
//

#import "MusicPlayViewController.h"
#import "DetailCellHelper2.h"
#import "MusicHelper.h"
#import "MusicView.h"
#import "VideoDownLoadManager.h"
#define kjianjieUrl @"http://mobile.ximalaya.com/mobile/track/detail?device=android&trackId="
@interface MusicPlayViewController ()<MusicHelperDelegate,UMSocialUIDelegate>

@property(nonatomic,strong)MusicView *musicView;
- (void)startPlay;
- (void)upDataUI;
@end

@implementation MusicPlayViewController
singleton_implementation(MusicPlayViewController)

- (void)loadView
{
    self.musicView = [[MusicView alloc] initWithFrame:CGRectMake(0, 64, kscreenwidth, kscreenHeight)];
    self.view = self.musicView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.musicView.slider addTarget:self action:@selector(playSliderAction:) forControlEvents:UIControlEventValueChanged];
    
    [self.musicView.playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.musicView.lastButton addTarget:self action:@selector(lastButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.musicView.nextButton addTarget:self action:@selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.musicView.zanButton addTarget:self action:@selector(zanButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.musicView.downButton addTarget:self action:@selector(downButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.musicView.shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
}

+ (instancetype)sharedInstance
{
    static MusicPlayViewController *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MusicPlayViewController alloc] init];
    });
    return manager;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.isAgo == YES) {
        return;
    }
    [self startPlay];
    [self upDataUI];
}

- (void)startPlay
{
    
    DetailModel2 *p = [DetailCellHelper2 sharedInstance].cellArray[self.index];
    [[MusicHelper sharedInstance] prepareWithUrl:p.playUrl64];
    [MusicHelper sharedInstance].delegate = self;
    self.isAgo = YES;
}
- (void)upDataUI
{
    DetailModel2 *p = [DetailCellHelper2 sharedInstance].cellArray[self.index];
    
    [self.musicView.imageV sd_setImageWithURL:[NSURL URLWithString:p.coverLarge]];
    [self.musicView.imageView sd_setImageWithURL:[NSURL URLWithString:p.coverLarge]];
    
    self.musicView.slider.maximumValue = p.duration;
    
    [self.musicView.playButton setBackgroundImage:[UIImage imageNamed:@"6"] forState:UIControlStateNormal];
    
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%ld",kjianjieUrl,p.trackId]]];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSString *str = dict[@"intro"];
        if (str == nil) {
            str = @"";
        }
        self.musicView.introL.text = [NSString stringWithFormat:@"%@,%@",dict[@"title"],str];
    }];
    
    self.musicView.zanImageView.image = [UIImage imageNamed:@""];
    self.musicView.downImageView.image = [UIImage imageNamed:@""];
    self.musicView.shareImageView.image = [UIImage imageNamed:@""];
    self.musicView.zanLabel.text = @"赞";
    self.musicView.zanLabel.textColor = [UIColor blackColor];
    self.musicView.downLabel.text = @"下载";
    self.musicView.downLabel.textColor = [UIColor blackColor];
    self.musicView.shareLabel.text = @"分享";
    self.musicView.shareLabel.textColor = [UIColor blackColor];
    self.title = p.title;
}

- (void)playWithAudioPlayer:(MusicHelper *)player withProgress:(CGFloat)progress
{
    DetailModel2 *p = [DetailCellHelper2 sharedInstance].cellArray[self.index];
    self.musicView.slider.value = progress;
    CGFloat time = p.duration - progress;
    self.musicView.totalL.text = [self playTime:time];
    self.musicView.startL.text = [self playTime:progress];
    
}

- (NSString *)playTime:(CGFloat)time
{
    NSInteger min = time / 60;
    NSInteger sec = (NSInteger)time % 60;
    return [NSString stringWithFormat:@"%ld:%ld",min,sec];
}

- (void)playEndFinish:(MusicHelper *)player
{
    [self nextButtonAction:nil];
}

// 上一首

- (void)lastButtonAction:(UIButton *)sender
{
    self.index--;
    
    if (self.index < 0) {
        self.index = [DetailCellHelper2 sharedInstance].cellArray.count - 1;
        
    }
    [self startPlay];
    [self upDataUI];
}



// 播放
- (void)playButtonAction:(UIButton *)sender
{
    if ([MusicHelper sharedInstance].isPlaying == YES) {
        [self.musicView.playButton setBackgroundImage:[UIImage imageNamed:@"9"] forState:UIControlStateNormal];
        [[MusicHelper sharedInstance] pause];
    }else{
        [self.musicView.playButton setBackgroundImage:[UIImage imageNamed:@"6"] forState:UIControlStateNormal];
        [[MusicHelper sharedInstance] play];
    }
}

// 下一首
- (void)nextButtonAction:(UIButton *)sender
{
    self.index++;
    if (self.index >= [DetailCellHelper2 sharedInstance].cellArray.count) {
        self.index = 0;
    }
    [self startPlay];
    [self upDataUI];
}

- (void)playSliderAction:(UISlider *)sender
{
    [[MusicHelper sharedInstance] seekToTime:sender.value];
}

- (void)zanButtonAction:(UIButton *)sender
{
    if ([LoginMangager sharedInstance].isLogin == YES) {
        sender.selected = !sender.isSelected;
        if (sender.selected) {
            self.musicView.zanImageView.image = [UIImage imageNamed:@""];
            self.musicView.zanLabel.text = @"已赞";
            self.musicView.zanLabel.textColor = [UIColor redColor];
        }else{
            self.musicView.zanImageView.image = [UIImage imageNamed:@""];
            self.musicView.zanLabel.text = @"赞";
            self.musicView.zanLabel.textColor = [UIColor blackColor];
        }
    }else{
        [[VideoDownLoadManager sharedInstance] startAVideoWithVideoModel:[DetailCellHelper2 sharedInstance].cellArray[self.index]];
    }
    
}

- (void)downButtonAction:(UIButton *)sender
{
    if ([LoginMangager sharedInstance].isLogin == YES) {
        [[VideoDownLoadManager sharedInstance] startAVideoWithVideoModel:[DetailCellHelper2 sharedInstance].cellArray[self.index]];
    }else{
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

- (void)shareButtonAction:(UIButton *)sender
{
    //[UMSocialSnsService presentSnsController:self appKey:@"562f8f9467e58e033700156b" shareText:nil shareImage:[UIImage imageNamed:@"blueArrow"] shareToSnsNames:[NSArray arrayWithObjects:UMShareToEmail,UMShareToSina, nil] delegate:self];
    if ([LoginMangager sharedInstance].isLogin == YES) {
        [UMSocialSnsService presentSnsIconSheetView:self appKey:@"562f8f9467e58e033700156b" shareText:nil shareImage:[UIImage imageNamed:@"blueArrow"] shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToSms,UMShareToTencent,UMShareToWechatSession,UMShareToWechatTimeline,UMShareToYXTimeline, nil] delegate:self];
    }else{
        LoginViewController *vc = [[LoginViewController alloc] init];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}




/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
